package xc.doughnut;

import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.Map;

/**
 * @author xuchao
 * @date 2024/1/26
 */
@Slf4j
public class ClazzCastEachOther {

    /**
     * Dto transform bean
     * @param clazzDto dto
     * @param wantClazz bean
     * @param mapTran 实现属性不同转换
     * @param <WZ>
     * @param <T>
     * @return
     */
    public static <WZ, T> WZ Dto2Bean(T clazzDto, Class<WZ> wantClazz, Map<String, String> mapTran) {
        try {
            WZ bean = wantClazz.getDeclaredConstructor().newInstance();
            // 获取DTO类的所有字段
            Field[] dtoFields = clazzDto.getClass().getDeclaredFields();

            for (Field dtoField : dtoFields) {
                // 获取字段名称
                String fieldName = dtoField.getName();
                dtoField.setAccessible(true);
                // 判断Map中是否有转化的属性
                String key = mapTran.get(fieldName);
                if (key != null) {
                    Field beanField = wantClazz.getDeclaredField(key);
                    // 获取DTO字段的值
                    beanField.setAccessible(true);
                    beanField.set(bean, dtoField.get(clazzDto));
                } else {
                    // 设置Bean相同名称的字段的值
                    try {
                        Field beanField = wantClazz.getDeclaredField(fieldName);
                        beanField.setAccessible(true);
                        beanField.set(bean, dtoField.get(clazzDto));
                    } catch (NoSuchFieldException e) {
                        log.warn(wantClazz+"类，没有 {} 属性", e.getMessage());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return bean;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public static void main(String[] args)  {
        // DTO
        // DemoDto dto = new DemoDto();
        // dto.setName("张三");
        // dto.setAge("20");
        // dto.setGender("男");

        // bean
        // Demo demo = new Demo();
        // 属性 name、age、sex

        // Map<String,  String> map = new HashMap<>();
        // map.put("gender", "sex");

        // Demo demo = ClazzCastEachOther.Dto2Bean(dto, Demo.class, map);
        // System.out.println(demo);
    }

}
